package com.aifund.app.websocket;

/**
 * 行情推送webSocket
 */

import com.aifund.common.entity.TokenEntity;
import com.aifund.common.enums.CommonEnum;
import com.aifund.common.enums.redis.RedisSetKey;
import com.aifund.common.result.ResultBody;
import com.aifund.common.service.SystemConfigService;
import com.aifund.common.util.JwtUtil;
import com.aifund.common.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.collections.RedisSet;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 行情推送webSocket
 * @ServerEndpoint(value = "/socket/market") 前端通过此URI和后端交互，建立连接
 */
@Slf4j
@ServerEndpoint(value = "/socket/market/{authToken}")
@Component
public class MarketPushWebSocket {

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 存放所有在线的客户端 */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    private static SystemConfigService systemConfigService;
    private static RedisTemplate redisTemplate;
    private static JwtUtil jwtUtil;

    @Autowired
    public void setJwtUtil(JwtUtil jwtUtil) {
        MarketPushWebSocket.jwtUtil = jwtUtil;
    }


    @Autowired
    public void setSystemConfigService(SystemConfigService systemConfigService) {
        MarketPushWebSocket.systemConfigService = systemConfigService;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        MarketPushWebSocket.redisTemplate = redisTemplate;
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("authToken")String authToken) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
        if(!validAuthToken(authToken)){
            log.info("拒绝链接", session.getId(), onlineCount.get());
            onClose(session);
            return;
        }
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        this.sendMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 群发消息
     * @param message  消息内容
     */
    public void sendMessage(String message, Session fromSession) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            // 排除掉自己
            if (!fromSession.getId().equals(toSession.getId())) {
                toSession.getAsyncRemote().sendText(message);
            }
        }
    }

    /**
     *
     * 群发消息
     * @param message  消息内容
     */
    public void sendMessage(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            toSession.getAsyncRemote().sendText(message);
        }
    }

    private boolean validAuthToken(String headerToken){
        //判断请求信息
        if(null==headerToken||"".equals(headerToken.trim())){
            return false;
        }
        //解析Token信息
        try {
            Claims claims = Jwts.parser().setSigningKey(systemConfigService.getJwtSecret()).parseClaimsJws(headerToken).getBody();
            String tokenUserId=(String)claims.get("userId");
            long iTokenUserId = Long.parseLong(tokenUserId);
            //根据客户Token查找数据库Token
            TokenEntity myToken = (TokenEntity) redisTemplate.opsForHash().entries(RedisSetKey.USER_TOKEN.getSetKey()).get(iTokenUserId + "");
            //数据库没有Token记录
            if(null==myToken) {
                return false;
            }
            //数据库Token与客户Token比较
            if( !headerToken.equals(myToken.getToken()) ){
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

}
